

/*
    定时器界面工作流程
1. 定时器是否已经在运行，如果在运行，切换为前台模式（关闭sw-timer)
2. 按键启动、暂停timer (停止暂时不支持，没有多余的地方放按钮)

暂停状态下，重载时间。这里重载按键变成停止按键
如果运行，则停止按键又变成重载。

简单的说，只能在暂停状态下，连接两次左边按键，才能停止计时器。

*/
#include "kb.h"                 // keybaord event type 
#include "touch_algorithm.h"    // touch event type 
#include "custom_event.h"
#include "gui.h"                // GUI header

#include "views.h"              // include all views 
#include "views_util.h"

#include "log.h"                // LOG file 
#define LOG     LOG_INFO0


#include "xapp_clock.h"
#include "xapp_timer.h"

enum tagTimerElapsed
{
    tagTimerElapsedPausePlay,
    tagTimerElapsedResetStop,
    tagTimerElapsedBack,
    tagTimerElapsedCreate, // 重建，从后台模式切换到前台模式
};

enum fsmTimerElapsed
{
    fsmTimerElapsedBackground,
    fsmTimerElapsedNormal,
};

enum flagTimerElapsed
{
    flagTimerElapsedPaintValue,
    flagTimerElapsedPaintButtons,
}; 

// declare function 
GUI_VIEW_FUNC_DECLARE_ALL;
static void local_view_event_handler( uint32_t tag );

static uint8_t time_value[12];
const static ui_widgets_type_t wglTimerElapsed/*1. modify name*/[] = 
{
    // set background black 
    [0] = uiCanvas(0, 0, GUI_LCD_RES_H, GUI_LCD_RES_V, COLOR_BLACK ),

    // icon 
    [1] = uiPictureBoxOverlay( IMG_Setting_Item_Icon_075_075_30, 8, SIZE_SCALE(95), SIZE_SCALE(27), SIZE_SCALE(50), SIZE_SCALE(50), COLOR_BLACK ),

    // timer elapsed
    [2] = uiNumberlistWithBuffer( SIZE_SCALE(60), SIZE_SCALE(90), GUI_LCD_RES_H-SIZE_SCALE(60), SIZE_SCALE(52), COLOR_BLACK, COLOR_WHITE, ALIGN_LEFT_TOP, FILL_NONE, ENCODING_ASCII, FONT_ASCII_1_40_52, "%02d:%02d:%02d", time_value, 12 ),

    // button pause/play
    [3] = uiSwitch( IMG_Setting_Stopwatch_Timer_Button_102_054_04, 1, 2, SIZE_SCALE(126), SIZE_SCALE(160), SIZE_SCALE(68), SIZE_SCALE(36) ),

    // button stop
    [4] = uiSwitch( IMG_Setting_Stopwatch_Timer_Button_102_054_04, 3, 0, SIZE_SCALE(46), SIZE_SCALE(160), SIZE_SCALE(68), SIZE_SCALE(36) ),    
};

const static ui_refresh_part_t partTimerElapsed[] = 
{
    [0] = xRECTANGLE( SIZE_SCALE(60), SIZE_SCALE(90), GUI_LCD_RES_H-SIZE_SCALE(60), SIZE_SCALE(52) ),
};

const static ui_widgets_type_t wglTimerElapsedTouch[] = 
{
    [0] = uiTouch( 0, SIZE_SCALE(160), SIZE_SCALE(120), SIZE_SCALE(80), tagTimerElapsedResetStop ),
    [1] = uiTouch( SIZE_SCALE(120), SIZE_SCALE(160), SIZE_SCALE(120), SIZE_SCALE(80), tagTimerElapsedPausePlay ),
};


GUI_VIEW_DEF_NR( viewTools_TimerElapsed ) = 
{
    // name 
    .name = "Tools+TimerElapsed",
    
    // init 
    .init = initialize,
    .display_func = display_callback_func,
    .refresh_func_check = display_refresh_func,
    .destroy_func = on_destroy_func,
    .set_parent_func = on_set_parent_func, 
    
    // input 
    .on_touch = on_touch,
    .on_button = on_button,
    .on_event_update = on_event_update,     
    
    .pWidgetlist =  (ui_widgets_type_t*)wglTimerElapsed /* 3. fill with widgets list name */,
    .widget_cnt = WIDGET_COUNT( wglTimerElapsed ), /* 3. fill with widgets list name */

    .flag = GUI_VIEW_FLAG_APP | GUI_VIEW_FLAG_BG_SUPPORTED
};


/* 当前view初始化
// 需要指定前使用的控件组
// 自动更新间隔，不使用自动更新间隔则interval = 0

*/
static void initialize(gui_menu_t * menu, void* pvParameter)
{
    menu->interval = 1000;
    menu->lifetime = 0;//5000;

    views_set_fsm( fsmTimerElapsedNormal ); 
    const xapp_timer_desc_t* p_timer_desc = xapp_timer_get();
    if( p_timer_desc->started )
    {
        xapp_timer_counting_foreground(); // 进入前台模式, 关闭sw-timer 
    }
}
static void on_set_parent_func(gui_menu_t * menu, const gui_view_t * parent)
{
//    p_this_parent = parent;
}
/* 销毁函数
// 在销毁前处理当前信息，比如不允许销毁时，将当前界面状态保存为background。
// true:  允许销毁
// false: 不允许自动销毁，则GUI只关闭当前显示，输入事件仍由当前view进行处理。
          那么view判断当前状态为background时，作出对应background下的按键、触摸等事件反馈
*/
static uint32_t on_destroy_func(gui_menu_t * menu)
{
    const xapp_timer_desc_t* p_timer_desc = xapp_timer_get();
    if( p_timer_desc->started && !p_timer_desc->paused ) // 非暂停状态，才允许进入背景模式
    {
        views_set_fsm( fsmTimerElapsedBackground );
        xapp_timer_counting_background(); // 开启sw-timer 定时唤醒更新值。
        return false; 
    }
 
    return GUI_DESTROY_RET_DEFAULT; 
}


/* 显示回调
   重新指定参数, 用来获取当前界面的控件组
   ** 当前界面有多个控件组时，应该有条件确定使用哪一组控件组 ** 
*/
static void display_callback_func(gui_menu_t * menu)
{
    ui_property_t prop;
    ui_widgets_type_t * widgets = menu->widgets;

    const xapp_timer_desc_t* p_timer_desc = xapp_timer_get_desc_real();

    if( IS_REQ_SRC_CREATE( menu->source ))
    {
        //if( menu->source == GUI_VIEW_REQ_SRC_CREATE )
        {
            gui_part_t gui_part = GUI_PART_CONFIG( partTimerElapsed, 1000 );
            gui_part_create( &gui_part );
            if( !p_timer_desc->started )
            {
                gui_part_stop();
            }             

        }
        FLAG_ALL();
    }

    if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_MANUAL )
    {
        FLAG_SETB( flagTimerElapsedPaintButtons );
        FLAG_SETB( flagTimerElapsedPaintValue );
    }

    if( menu->source == GUI_VIEW_REQ_SRC_UPDATE_PART )
    {
        FLAG_SETB( flagTimerElapsedPaintValue ); 
    }
    

    if( FLAG_GETB( flagTimerElapsedPaintValue ))
    {
        uint8_t hour = p_timer_desc->seconds / 3600;
        uint8_t minutes = p_timer_desc->seconds % 3600 / 60;
        uint8_t seconds = p_timer_desc->seconds % 60;
        // GUI_LOG3("[TIMER]: %d H %d M %d S", hour, minutes, seconds );
        PROP_ASSIGN_NUMBERLIST_3( prop, hour, minutes, seconds );
        PROP_UPDATE_AT_NO( 2 ); 
    }

    if( FLAG_GETB( flagTimerElapsedPaintButtons ))
    {
        // 按键可见识别
        if( p_timer_desc->paused || !p_timer_desc->started ) // 正在暂停 和 未启动
        {
            PROP_ASSIGN_SWITCH_ONOFF( prop, true );
        }
        else // 启动后，仅有一个暂停
        {
            PROP_ASSIGN_SWITCH_ONOFF( prop, false );
        }
        PROP_UPDATE_AT_NO( 3 );

        if( p_timer_desc->paused )
        {
            PROP_ASSIGN_SWITCH_ONOFF( prop, true );
        }
        else 
        {
            PROP_ASSIGN_SWITCH_ONOFF( prop, false );
        }
        PROP_UPDATE_AT_NO( 4 );
    }

    FLAG_CLEAR();
}

/* 刷新显示回调
   根据当前状态，重新绘制指定的控件组 
*/
static int display_refresh_func(gui_menu_t * menu)
{
    return 1;
}

static void on_touch(void* pvParameters, gui_menu_t * menu)
{
    tp_algo_evt_t* touch = (tp_algo_evt_t*)pvParameters;

    switch( touch->type )
    {
        case TP_ALGO_EVT_TYPE_CLICK:
        {
            uint32_t fsm = views_fsm_get();
            if( fsm == fsmTimerElapsedNormal )
            {
                VIEW_CHECK_TOUCH(wglTimerElapsedTouch, touch->x, touch->y, local_view_event_handler );
            }
            else if( fsm == fsmTimerElapsedBackground )
            {
                gui_view_create( &viewTools_TimerElapsed ); 
            }
        }
        break;

        case TP_ALGO_EVT_TYPE_SLIDE_R:
        {
            local_view_event_handler( tagTimerElapsedBack );
        }
        break;
        
        default:
        break;
    }
}
/* 界面的按键处理

*/
static void on_button(void* pvParameters, gui_menu_t * menu)
{
    kb_evt_t * kb = (kb_evt_t*)pvParameters;
    
    switch( kb->type ) 
    {
        case KB_EVT_CLICK:           
        case KB_EVT_SHORT_HOLD_READY:
        {
            uint32_t fsm = views_fsm_get();
            if( fsm == fsmTimerElapsedBackground )
            {
                local_view_event_handler( tagTimerElapsedCreate );
            }
            else 
            {
                local_view_event_handler( tagTimerElapsedBack );
            }
        }
        break;

        default:
            break;
    }
 
}

/* 界面的自定义输入事件处理

*/
static void on_event_update(void * pvParameters, gui_menu_t * menu)
{
    custom_evt_t* custom = (custom_evt_t*)pvParameters;
    switch( custom->type )
    {
        case CUSTOM_EVT_TYPE_RAISE_WRIST:
        break;

        case CUSTOM_EVT_TYPE_DROP_WRIST:
        break;
        
        default:
        break;
    }
}

/* 界面的触摸事件
   tag 是生效的控件id, 用户根据生效的tag判断是哪个控件点击了，进行处理
*/
static void local_view_event_handler( uint32_t tag )
{
    switch( tag )
    {
        case tagTimerElapsedResetStop:
        {
            const xapp_timer_desc_t* p_timer_desc = xapp_timer_get_desc_real();            

            if( p_timer_desc->paused  )
            {
                xapp_timer_counting_stop();
            }
            else 
            {
                xapp_timer_counting_reset();
            }
            gui_update_manual();
        }
        break;

        case tagTimerElapsedPausePlay:
        {
            const xapp_timer_desc_t* p_timer_desc = xapp_timer_get_desc_real();
            if( p_timer_desc->paused || !p_timer_desc->started )
            {
                xapp_timer_counting_start();
                gui_part_start();
                GUI_LOG0("[TIMER]:START");                
            }
            else 
            {
                xapp_timer_counting_pause();
                gui_part_stop();
                GUI_LOG0("[TIMER]:STOP");
            }
            gui_update_manual();
        }
        break;


        case tagTimerElapsedBack:
        {
            const xapp_timer_desc_t* p_timer_desc = xapp_timer_get();
            if( !p_timer_desc->paused ) // 如果暂停中，需要修改定时值; 否则返回应用界面 
            {
                gui_view_create_return( &viewAppsList );
            }
            else 
            {
                gui_view_create_return( &viewTools_TimerSelect );
            }
        }
        break;

        case tagTimerElapsedCreate:
        gui_view_create( &viewTools_TimerElapsed );
        break;
    }
}
